using System;
using System.IO;
using System.Windows.Forms;
using System.Collections.Generic;

namespace CopyTool
{
    public partial class CopyToolForm : Form
    {
        private string logFilePath = "copy_log.txt";
        
        public CopyToolForm()
        {
            InitializeComponent();
            cbReplaceFolder.Enabled=false;
            txtSource.Enabled = false;
        }

        private void LogOperation(string message)
        {
            string logEntry = $"[{DateTime.Now}] {message}{Environment.NewLine}";
            File.AppendAllText(logFilePath, logEntry);
        }

        private void btnSelectSource_Click(object sender, EventArgs e)
        {
            if (rbFile.Checked)
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Multiselect = true;
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    txtSource.Text = string.Join("; ", openFileDialog.FileNames);
                }
            }
            else
            {
                FolderBrowserDialog folderDialog = new FolderBrowserDialog();
                if (folderDialog.ShowDialog() == DialogResult.OK)
                {
                    txtSource.Text = folderDialog.SelectedPath;
                }
            }
        }

        private void btnSelectTarget_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderDialog = new FolderBrowserDialog();
            if (folderDialog.ShowDialog() == DialogResult.OK)
            {
                txtTarget.Text = folderDialog.SelectedPath;
            }
        }

        private void btnCopy_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtSource.Text) || string.IsNullOrEmpty(txtTarget.Text))
            {
                MessageBox.Show("请先选择源和目标路径");
                return;
            }

            try
            {
                if (rbFile.Checked)
                {
                    CopyFile(txtSource.Text, txtTarget.Text);
                }
                else
                {
                    CopyFolder(txtSource.Text, txtTarget.Text);
                }
                
                MessageBox.Show("复制完成");
                LogOperation($"成功复制 {txtSource.Text} 到 {txtTarget.Text}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"复制失败: {ex.Message}");
                LogOperation($"复制失败: {ex.Message}");
            }
        }

        private void CopyFile(string sourceFile, string targetDir)
        {
            // 处理多个文件的情况
            string[] files = sourceFile.Split(new[] {"; "}, StringSplitOptions.RemoveEmptyEntries);
            
            foreach (string file in files)
            {
                string fileName = Path.GetFileName(file);
                string finalTargetPath = GetFinalTargetPath(file, targetDir);
                if (string.IsNullOrEmpty(finalTargetPath))
                {
                    throw new ArgumentNullException(nameof(finalTargetPath), "目标路径不能为空");
                }
                
                string destFile = Path.Combine(finalTargetPath, fileName);
                
                string destDir = Path.GetDirectoryName(destFile);
                if (!string.IsNullOrEmpty(destDir))
                {
                    Directory.CreateDirectory(destDir);
                }
                File.Copy(file, destFile, true);
            }
        }

        private void CopyFolder(string sourceDir, string targetDir)
        {
            if (string.IsNullOrEmpty(sourceDir))
            {
                throw new ArgumentNullException(nameof(sourceDir), "源目录不能为空");
            }

            DirectoryInfo dir = new DirectoryInfo(sourceDir);
            string finalTargetDir = GetFinalTargetPath(sourceDir, targetDir);
            
            if (string.IsNullOrEmpty(finalTargetDir))
            {
                throw new ArgumentNullException(nameof(finalTargetDir), "目标目录不能为空");
            }
            
            // 创建目标目录
            Directory.CreateDirectory(finalTargetDir);

            // 复制所有文件
            foreach (FileInfo file in dir.GetFiles())
            {
                string tempPath = Path.Combine(finalTargetDir, file.Name);
                file.CopyTo(tempPath, true);
            }

            // 递归复制子目录
            foreach (DirectoryInfo subDir in dir.GetDirectories())
            {
                string tempPath = Path.Combine(finalTargetDir, subDir.Name);
                CopyFolder(subDir.FullName, tempPath);
            }
        }

        private void txtSource_TextChanged(object sender, EventArgs e)
        {
            cbReplaceFolder.Enabled = !string.IsNullOrEmpty(txtSource.Text);
            cbReplaceFolder.Items.Clear();
            
            if (cbReplaceFolder.Enabled)
            {
                string path = txtSource.Text;
                
                // 如果是文件路径，获取所在目录
                if (File.Exists(path))
                {
                    path = Path.GetDirectoryName(path);
                }
                
                // 添加所有父目录（从最上层到最下层）
                List<string> paths = new List<string>();
                while (!string.IsNullOrEmpty(path))
                {
                    paths.Insert(0, path); // 插入到列表开头，保持从最上层到最下层的顺序
                    path = Path.GetDirectoryName(path);
                }
                
                // 添加整理好的路径
                foreach (var p in paths)
                {
                    cbReplaceFolder.Items.Add(p);
                }
                
                // 添加源路径本身（如果是目录）
                if (Directory.Exists(txtSource.Text))
                {
                    cbReplaceFolder.Items.Add(txtSource.Text);
                }
                
                if (cbReplaceFolder.Items.Count > 0)
                {
                    cbReplaceFolder.SelectedIndex = 0;
                }
            }
            
            // 更新标签状态
            label3.Enabled = cbReplaceFolder.Enabled;
        }

        private string GetFinalTargetPath(string sourcePath, string targetDir)
        {
            if (string.IsNullOrEmpty(sourcePath))
            {
                throw new ArgumentNullException(nameof(sourcePath), "源路径不能为空");
            }
            
            if (string.IsNullOrEmpty(targetDir))
            {
                throw new ArgumentNullException(nameof(targetDir), "目标目录不能为空");
            }
            
            if (cbReplaceFolder?.SelectedItem != null)
            {
                string replaceFrom = cbReplaceFolder.SelectedItem.ToString().Trim();
                
                // 确保替换目录是源目录的一部分
                if (!sourcePath.StartsWith(replaceFrom, StringComparison.OrdinalIgnoreCase))
                {
                    MessageBox.Show($"替换目录 '{replaceFrom}' 不是源目录 '{sourcePath}' 的一部分");
                    return targetDir;
                }

                // 确保替换目录是有效的目录路径
                if (!replaceFrom.EndsWith(Path.DirectorySeparatorChar.ToString()))
                {
                    replaceFrom += Path.DirectorySeparatorChar;
                }

                // 统一处理文件和目录路径，都保留相对路径结构
                string relativePath = sourcePath.Substring(replaceFrom.Length).TrimStart(Path.DirectorySeparatorChar);
                
                // 如果是文件路径，移除文件名部分
                if (File.Exists(sourcePath))
                {
                    relativePath = Path.GetDirectoryName(relativePath);
                }
                
                return Path.Combine(targetDir, relativePath);
            }
            return targetDir;
        }
    }
}